// Fill out your copyright notice in the Description page of Project Settings.

#include "HealthComponent.h"
#include "Net/UnrealNetwork.h"
#include "SimpleAIPawn.h"


// Sets default values for this component's properties
UHealthComponent::UHealthComponent()
{
	// Set this component to be initialized when the game starts, and to be ticked every frame.  You can turn these features
	// off to improve performance if you don't need them.
	PrimaryComponentTick.bCanEverTick = true;

	Health = 100.f;

	bReplicates = true;
	// ...
}


// Called when the game starts
void UHealthComponent::BeginPlay()
{
	Super::BeginPlay();

	//InitHealth();

	AActor* MyOwner = GetOwner();
	if (MyOwner)
	{
		MyOwner->OnTakeAnyDamage.AddDynamic(this, &UHealthComponent::HandleOnTakeAnyDamage);
	}
	
}


void UHealthComponent::InitHealth()
{
	Health = GetMaxHealth();
}

void UHealthComponent::HandleOnTakeAnyDamage(AActor* DamagedActor, float Damage, 
		const class UDamageType* DamageType, class AController* InstigatedBy, AActor* DamageCauser)
{
	if (Damage <= 0) return;

	Health = FMath::Clamp(Health - Damage, 0.f, GetMaxHealth());
	OnHealthChanged.Broadcast(this, Health, Damage, DamageType, InstigatedBy, DamageCauser);
	//UE_LOG(LogClass, Warning, TEXT("Health : %s"), *FString::SanitizeFloat(Health));
}



// Called every frame
void UHealthComponent::TickComponent(float DeltaTime, ELevelTick TickType, FActorComponentTickFunction* ThisTickFunction)
{
	Super::TickComponent(DeltaTime, TickType, ThisTickFunction);

	// ...
}

float UHealthComponent::GetMaxHealth() const
{
	return  GetClass()->GetDefaultObject<UHealthComponent>()->Health * 10.f;
}

void UHealthComponent::GetLifetimeReplicatedProps(TArray<FLifetimeProperty>& OutLifetimeProps) const
{
	Super::GetLifetimeReplicatedProps(OutLifetimeProps);
	DOREPLIFETIME(UHealthComponent, Health);
}

void UHealthComponent::UpdateHealth(float HealthValue)
{
	if (GetOwnerRole() < ROLE_Authority)
	{
		ServerUpdateHealth(HealthValue);
		return;
	}

	Health = FMath::Clamp(Health + HealthValue, 0.f, GetMaxHealth());
}

void UHealthComponent::ServerUpdateHealth_Implementation(float HealthValue)
{
	UpdateHealth(HealthValue);
}

bool UHealthComponent::ServerUpdateHealth_Validate(float HealthValue)
{
	return true;
}